package com.chain.BrotherExchange.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.event.SubmitLevel2CertificationEvent;
import com.chain.BrotherExchange.ui.core.BaseActivity;
import com.chain.BrotherExchange.utils.ActivityBarHelper;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.viewmodel.IDAuthenticationViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;
import com.example.common.widget.state.NetworkStateLayout;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.Bind;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 二级认证
 */
public class Level2CertificationActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    @Bind(R.id.apply_button) View mApplyButton;
    @Bind(R.id.front_id_card_image) ImageView frontIdCardImage;
    @Bind(R.id.front_id_card_hint_image) ImageView frontIdCardHintImage;
    @Bind(R.id.front_id_card_layout) FrameLayout frontIdCardLayout;
    @Bind(R.id.reverse_side_id_card_image) ImageView reverseSideIdCardImage;
    @Bind(R.id.reverse_side_id_card_hint_image) ImageView reverseSideIdCardHintImage;
    @Bind(R.id.reverse_side_id_card_layout) FrameLayout reverseSideIdCardLayout;
    @Bind(R.id.hand_identity_card_image) ImageView handIdentityCardImage;
    @Bind(R.id.hand_identity_card_hint_image) ImageView handIdentityCardHintImage;
    @Bind(R.id.hand_identity_card_layout) FrameLayout handIdentityCardLayout;
    @Bind(R.id.name_text) TextView mNameTextView;
    @Bind(R.id.id_number_text) TextView mIdNumberTextView;
    @Bind(R.id.network_state_layout) NetworkStateLayout mNetworkStateLayout;

    private int selectReq;
    private IDAuthenticationViewModel mViewModel;
    private Uri mFrontIdCardUri, mReverseSideIdCardUri, mHandIdCardUri;

    public static void launch(Context context) {
        context.startActivity(new Intent(context, Level2CertificationActivity.class));
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_level_2_certification;
    }

    @Override
    protected void initActions() {
        ActivityBarHelper.init(this, R.string.title_level_2_certification);

        // 逻辑
        mViewModel = ViewModelProviders.of(this).get(IDAuthenticationViewModel.class);

        // 身份证信息
        initAuthenticationInfo();

        // 身份证正面
        frontIdCardLayout.setOnClickListener(v -> selectFrontIdCard());

        // 身份证反面
        reverseSideIdCardImage.setOnClickListener(v -> selectReverseSideIdCard());

        // 手持身份证
        handIdentityCardLayout.setOnClickListener(v -> selectHandIdentityCard());

        // 提交认证
        mApplyButton.setOnClickListener(v -> submitCertification());
    }

    private void submitCertification() {
        if (mFrontIdCardUri == null) {
            Androids.makeText(R.string.message_please_positive_photo_id_card);
            return;
        }

        if (mReverseSideIdCardUri == null) {
            Androids.makeText(R.string.message_please_id_card_instead_photo);
            return;
        }

        if (mHandIdCardUri == null) {
            Androids.makeText(R.string.message_please_photo_your_handheld_id);
            return;
        }

        mViewModel.level2Certification().observe(this, resource -> {
            if (resource.state == Resource.Status.LOADING) {
                Androids.showProgressMessage(this, R.string.message_submitting_photo_ing);
            } else {
                Androids.dismissProgressMessage();
                Androids.makeText(resource.message);
                if (resource.state == Resource.Status.SUCCESS) {
                    EventBus.getDefault().post(new SubmitLevel2CertificationEvent());
                    finish();
                }
            }
        });
    }

    private void initAuthenticationInfo() {
        mViewModel.isAuthentication().observe(this, resource -> {
            Resource.load(this, resource, mNetworkStateLayout, result -> {
                mNameTextView.setText(result.getEncryptRealName());
                mIdNumberTextView.setText(result.getEncryptRealId());
            });
        });
    }

    private void selectHandIdentityCard() {
        selectPicture(C.REQ_HAND_ID_CARD);
    }

    private void selectFrontIdCard() {
        selectPicture(C.REQ_FRONT_ID_CARD);
    }

    private void selectReverseSideIdCard() {
        selectPicture(C.REQ_REVERSE_SIDE_ID_CARD);
    }

    private void selectPicture(int req) {
        selectReq = req;
        String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, permissions)) {
            String rationale = getString(R.string.please_approve_camera_permissions);
            EasyPermissions.requestPermissions(this, rationale, 0, permissions);
            return;
        }

        Matisse.from(this)
                .choose(MimeType.allOf())
                .countable(true)
                .maxSelectable(1)
                .theme(R.style.Matisse_UNT)
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(req);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        selectPicture(selectReq);
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle(R.string.auto_authorization_failure)
                    .setRationale(R.string.please_manually_select_approve_camera_permissions).build().show();
        } else {
            Androids.makeText(R.string.authorization_failure);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            selectPicture(selectReq);
        } else if (requestCode == C.REQ_FRONT_ID_CARD && resultCode == RESULT_OK) {
            mFrontIdCardUri = Matisse.obtainResult(data).get(0);
            frontIdCardImage.setImageURI(mFrontIdCardUri);
            //frontIdCardHintImage.setVisibility(View.INVISIBLE);
            upload(frontIdCardImage, 1, frontIdCardHintImage);
        } else if (requestCode == C.REQ_REVERSE_SIDE_ID_CARD && resultCode == RESULT_OK) {
            mReverseSideIdCardUri = Matisse.obtainResult(data).get(0);
            reverseSideIdCardImage.setImageURI(mReverseSideIdCardUri);
            //reverseSideIdCardHintImage.setVisibility(View.INVISIBLE);
            upload(reverseSideIdCardImage, 2, reverseSideIdCardHintImage);
        } else if (requestCode == C.REQ_HAND_ID_CARD && resultCode == RESULT_OK) {
            mHandIdCardUri = Matisse.obtainResult(data).get(0);
            handIdentityCardImage.setImageURI(mHandIdCardUri);
            //handIdentityCardHintImage.setVisibility(View.INVISIBLE);
            upload(handIdentityCardImage, 3, handIdentityCardHintImage);
        }
    }

    private void upload(ImageView imageView, int type, ImageView hint) {
        mViewModel.uploadFile(imageView, type).observe(this, resource -> {
            if (resource.state == Resource.Status.LOADING) {
                Androids.showProgressMessage(this, R.string.message_uploading);
            } else {
                Androids.dismissProgressMessage();
                Androids.makeText(resource.message);
                hint.setVisibility(View.INVISIBLE);
                if (resource.state == Resource.Status.ERROR) {
                    hint.setVisibility(View.VISIBLE);
                }
            }
        });
    }
}
